
package com.gamatechno.solodestinationnew;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.view.CardGridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.gamatechno.solodestinationnew.CategoryActivity.Holder;
import com.gamatechno.solodestinationnew.adapter.AdapterSearch;
import com.gamatechno.solodestinationnew.entity.E_Location;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.model.LatLng;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class SearchActivity extends BaseActivity implements OnConnectionFailedListener,
        ConnectionCallbacks, OnItemClickListener {

    private LocationClient mLocationClient;
    private Location location;

    private int category;
    private String query;
    private ListView lvSearch;
    private AdapterSearch adapter;
    private CardGridView cardGridView;
    private ProgressBar pBar;
    private HashMap<String, String> params;
    private List<E_Location> listLocation;
    private List<Card> listCard;
    private String imgPath;
    private double jarak;
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        mLocationClient = new LocationClient(this, this, this);
        listCard = new ArrayList<Card>();

        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");

        // cardGridView = (CardGridView) findViewById(R.id.grid_search);
        pBar = (ProgressBar) findViewById(R.id.loader_search);
        lvSearch = (ListView) findViewById(R.id.lv_search);

        lvSearch.setEmptyView(findViewById(android.R.id.empty));
        listLocation = new ArrayList<E_Location>();

        adapter = new AdapterSearch(this, listLocation);
        lvSearch.setAdapter(adapter);

        lvSearch.setOnItemClickListener(this);

        handelIntent(getIntent());
    }

    private void showLoading(boolean state) {
        // cardGridView.setVisibility((state) ? View.GONE : View.VISIBLE);
        lvSearch.setVisibility((state) ? View.GONE : View.VISIBLE);
        findViewById(android.R.id.empty).setVisibility((state) ? View.GONE : View.VISIBLE);
        pBar.setVisibility((state) ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        handelIntent(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mLocationClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.disconnect();
    }

    private void handelIntent(Intent intent) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            query = intent.getStringExtra(SearchManager.QUERY);
            Toast.makeText(this, "Cari : " + query, Toast.LENGTH_SHORT).show();
            searchData(Webservice.SEARCH_DATA);
        }
    }

    private void searchData(String URL) {
        StringRequest request = new StringRequest(Request.Method.POST,
                URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Utils.TRACE("SearchActivity.searchData(...).new StringRequest() {...}",
                                "searchData : " + response);
                        showLoading(false);
                        try {
                            JSONObject obj = new JSONObject(response);
                            if (obj.getInt("status") == 200) {
                                if (obj.getJSONArray("result").length() > 0) {
                                    List<E_Location> tmp = JSONHelper.searchLocation(
                                            obj.getJSONArray("result"),
                                            new LatLng(location.getLatitude(), location
                                                    .getLongitude()));
                                    listLocation.addAll(tmp);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE("SearchActivity.searchData(...).new StringRequest() {...}",
                                "searchData : " + error.toString());
                        Utils.showVolleyError(SearchActivity.this, error);
                        showLoading(false);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params = new HashMap<String, String>();
                params.put("method", "search");
                params.put("format", "json");
                params.put("language",
                        Utils.getDataStringFromSP(SearchActivity.this, Utils.PREF_BAHASA));
                params.put("keyword", query);
                return params;
            }
        };
        showLoading(true);
        BaseApplication.getInstance().addToRequestQueue(request, "SEARCH");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // getMenuInflater().inflate(R.menu.search, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        // TODO Auto-generated method stub
        if (mLocationClient.isConnected())
        {
            location = mLocationClient.getLastLocation();
            if (location != null) {
                Utils.TRACE("SearchActivity", "onConnected : location found");
                // locationFound = true;
            }
        }
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
        if (result.hasResolution()) {
            Toast.makeText(this, "Result Has Resolution", Toast.LENGTH_LONG).show();
            try {
                result.startResolutionForResult(this, 1);
            } catch (IntentSender.SendIntentException e) {
                Log.d("error", "" + e.getMessage());
            }
        } else {
            Toast.makeText(this, "No Resolution", Toast.LENGTH_LONG).show();
        }
    }

    private class CardLocation extends Card {
        private String gambar, title, jarak, desc;
        private float rate;
        private double lat, lng;

        public CardLocation(Context context, int id, String gambar, String title, String desc,
                String jarak,
                float rate, double lat, double lng) {
            super(context, R.layout.item_card_grid_category);
            setId("" + id);
            this.desc = desc;
            this.gambar = gambar;
            this.title = title;
            this.jarak = jarak;
            this.rate = rate;
            this.lat = lat;
            this.lng = lng;
            init();
        }

        private void init() {
            // TODO Auto-generated method stub
            setOnClickListener(new OnCardClickListener() {

                @Override
                public void onClick(Card card, View view) {
                    Bundle data = new Bundle();
                    data.putString("title", title);
                    data.putString("id", card.getId());
                    data.putString("img", gambar);
                    data.putString("desc", desc);
                    data.putString("distance", jarak);
                    data.putFloat("rating", rate);
                    data.putDouble("lat", lat);
                    data.putDouble("lng", lng);
                    data.putInt("cat", category);

                    startActivity(new Intent(SearchActivity.this, DetailLocationActivity.class)
                            .putExtras(data));
                }
            });
        }

        @Override
        public void setupInnerViewElements(ViewGroup parent, View view) {
            // super.setupInnerViewElements(parent, view);
            Holder holder = new Holder();

            holder.distance = (TextView) view.findViewById(R.id.txt_distance);
            holder.title = (TextView) view.findViewById(R.id.title_location);
            holder.rating = (RatingBar) view.findViewById(R.id.rating_category);

            final ImageView thumb = (ImageView)
                    view.findViewById(R.id.thumb_location);

            final ProgressBar pBar = (ProgressBar)
                    view.findViewById(R.id.loader);

            ImageLoader.getInstance().displayImage(gambar, thumb,
                    BaseApplication.getDisplayImageOptions(),
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            // TODO Auto-generated method stub
                            super.onLoadingComplete(imageUri, view, loadedImage);
                            if (pBar != null) {
                                pBar.setVisibility(View.GONE);
                                thumb.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onLoadingStarted(String imageUri, View view) {
                            super.onLoadingStarted(imageUri, view);
                            if (thumb != null)
                            {
                                thumb.setVisibility(View.GONE);
                                pBar.setVisibility(View.VISIBLE);
                            }
                        }
                    });

            holder.title.setText(this.title);
            holder.distance.setText(jarak + " km");
            holder.rating.setRating(rate);

        }

    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
        // Toast.makeText(this, "" + ((E_Location)
        // adapter.getItem(pos)).getKategori(), Toast.LENGTH_SHORT)
        // .show();

        int id = ((E_Location) adapter.getItem(pos)).getId();
        jarak = ((E_Location) adapter.getItem(pos)).getJarak();

        int cat = 0;
        String category = ((E_Location) adapter.getItem(pos)).getKategori();

        if (category.equals("Belanja")) {
            cat = MainActivity.CATEGORY_SHOPPING;
        } else if (category.equals("Kuliner")) {
            cat = MainActivity.CATEGORY_KULINER;
        } else if (category.equals("Hotel")) {
            cat = MainActivity.CATEGORY_HOTEL;
        } else if (category.equals("Kerajinan")) {
            cat = MainActivity.CATEGORY_HANDYCRAFT;
        } else if (category.equals("Wisata")) {
            cat = MainActivity.CATEGORY_TOURISM;
        }

        String lang = Utils.getDataStringFromSP(this, Utils.PREF_BAHASA);

        switch (cat) {
            case MainActivity.CATEGORY_SHOPPING:
                getDetailSearch(Webservice.GET_DETAIL_SEARCH_SHOPPING(id,
                        lang), cat, id);
                break;
            case MainActivity.CATEGORY_KULINER:
                getDetailSearch(Webservice.GET_DETAIL_SEARCH_KULINER(id, lang), cat, id);
                break;
            case MainActivity.CATEGORY_HOTEL:
                getDetailSearch(Webservice.GET_DETAIL_SEARCH_HOTEL(id, lang), cat, id);
                break;
            case MainActivity.CATEGORY_HANDYCRAFT:
                getDetailSearch(Webservice.GET_DETAIL_SEARCH_KERAJINAN(id, lang), cat, id);
                break;
            case MainActivity.CATEGORY_TOURISM:
                getDetailSearch(Webservice.GET_DETAIL_SEARCH_WISATA(id, lang), cat, id);
                break;
        }

    }

    private void getDetailSearch(String URL, final int category, final int id) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        // showLoading(false);
                        pDialog.dismiss();
                        Utils.TRACE("SearchActivity.getDetailSearch(...).new Listener() {...}",
                                "getDetailSearch : " + response.toString());

                        try {
                            if (response.getInt("status") == 200) {
                                JSONObject objek = response.getJSONObject("result");
                                imgPath = Webservice.GET_IMG_DIR(category,
                                        objek.getString("images"));

                                Bundle data = new Bundle();
                                data.putInt("cat", category);
                                data.putString("id", "" + id);
                                data.putFloat("rating", (float) objek.getDouble("rating"));
                                data.putString("title", objek.getString("name"));
                                data.putDouble("distance", jarak);
                                data.putString("desc", objek.getString("description"));
                                data.putDouble("lat", objek.getDouble("lat"));
                                data.putDouble("lng", objek.getDouble("lng"));
                                data.putString("img", imgPath);

                                startActivity(new Intent(SearchActivity.this,
                                        DetailLocationActivity.class).putExtras(data));

                            } else {
                                Utils.TRACE(
                                        "SearchActivity.getDetailSearch(...).new Listener() {...}",
                                        "onResponse : kosong");
                            }
                        } catch (JSONException e) {
                            Utils.TRACE("SearchActivity.getDetailSearch(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());
                        }
                    }

                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // showLoading(false);
                        pDialog.dismiss();
                        Utils.TRACE(
                                "SearchActivity.getDetailSearch(...).new ErrorListener() {...}",
                                "getDetailSearch : " + error.getMessage());
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, "SEARCH");
        // showLoading(true);
        pDialog.show();
    }
}
